const {Editor} = require('../database/index');
const {sendResponse} = require("../untils");

// -------------------------- 核心功能实现 --------------------------

/**
 * 添加编辑器内容
 */
const addEditor = async (ctx) => {
    try {
        const {html, src, copy_writing} = ctx.request.body;

        // 参数验证：至少提供一项内容
        if (!html && !src && !copy_writing) {
            return sendResponse(ctx, 400, "至少需要提供一项内容", []);
        }

        // 创建记录
        const editor = await Editor.create({
            html,
            src,
            copy_writing
        });

        sendResponse(ctx, 200, "创建成功", editor);
    } catch (error) {
        console.error("添加编辑器内容异常:", error);
        sendResponse(ctx, 500, "创建失败", error.message);
    }
};

/**
 * 获取所有编辑器内容
 */
const getEditor = async (ctx) => {
    try {
        // 查询所有记录（可扩展支持分页）
        const allEditor = await Editor.findAll();
        sendResponse(ctx, 200, "获取wangEditor案例成功", allEditor);
    } catch (error) {
        console.error("获取编辑器内容异常:", error);
        sendResponse(ctx, 500, "查询失败", error.message);
    }
};

/**
 * 编辑编辑器内容
 */
const editEditor = async (ctx) => {
    try {
        const {id, html, src, copy_writing} = ctx.request.body;

        // 参数验证：必须提供ID
        if (!id) {
            return sendResponse(ctx, 400, "缺少ID参数", []);
        }

        // 执行更新并获取受影响的行数
        const [affectedCount] = await Editor.update(
            {html, src, copy_writing},
            {where: {id}}
        );

        // 根据更新结果返回对应响应
        if (affectedCount > 0) {
            sendResponse(ctx, 200, "编辑成功", []);
        } else {
            sendResponse(ctx, 404, "未找到对应记录或内容未变更", []);
        }
    } catch (error) {
        console.error("编辑编辑器内容异常:", error);
        sendResponse(ctx, 500, "编辑失败", error.message);
    }
};

// -------------------------- 路由配置 --------------------------
const editorRoutes = [
    {type: 'post', url: '/editor/addEditor', method: addEditor},
    {type: 'post', url: '/editor/getEditor', method: getEditor},
    {type: 'post', url: '/editor/editEditor', method: editEditor},
];

module.exports = editorRoutes;
